package com.conversationboard.controller;

import java.io.IOException;
import java.sql.SQLException;
import java.util.Date;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.conversationboard.config.Configuration;
import com.conversationboard.logger.LogMessageType;
import com.conversationboard.logger.Logger;
import com.conversationboard.model.User;
import com.conversationboard.site.Site;
import com.conversationboard.validate.InputChecker;
import com.conversationboard.validate.bbcode.Validator;

@WebServlet(name = "AdminUpdateSiteConfigurationServlet", urlPatterns = "/Admin/AdminUpdateSiteConfigurationServlet")
public class AdminUpdateSiteConfigurationServlet extends HttpServlet {

	private static final long serialVersionUID = 6398735064407181116L;


	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		try {
			request.setCharacterEncoding("UTF-8");
			response.setCharacterEncoding("UTF-8");

			/*
			 * Pick up all the variables from the form and update the
			 * configuration
			 */

			User user = User.get(request.getUserPrincipal());

			if (!SecurityChecks.passes(request, user, this)) {
				return;
			}

			Configuration config = Configuration.getInstance();

			config.setSiteName(request.getParameter("siteName"));

			if (request.getParameter("allowUserBoardCreation") != null) {
				config.setAllowUserBoardCreation(true);
			} else {
				config.setAllowUserBoardCreation(false);
			}

			if (request.getParameter("allowHtmlPosts") != null) {
				config.setAllowHtmlPosts(true);
			} else {
				config.setAllowHtmlPosts(false);
			}

			if (request.getParameter("allowBlockRegistration") != null) {
				config.setAllowBlockRegistration(true);
			} else {
				config.setAllowBlockRegistration(false);
			}

			if (request.getParameter("checkForDuplicateMessages") != null) {
				config.setCheckForDuplicateMessages(true);
			} else {
				config.setCheckForDuplicateMessages(false);
			}

			if (request.getParameter("displayHumanTimes") != null) {
				config.setDisplayHumanTimes(true);
			} else {
				config.setDisplayHumanTimes(false);
			}

			if (request.getParameter("displayNumberOfRecentMessages") != null) {
				config.setDisplayNumberOfRecentMessages(true);
			} else {
				config.setDisplayNumberOfRecentMessages(false);
			}

			config.setOldestMessageCount(Integer.parseInt(request.getParameter("oldestMessageCount")));
			config.setNewestMessageCount(Integer.parseInt(request.getParameter("newestMessageCount")));
			config.setMaxThreadCacheEntries(Integer.parseInt(request.getParameter("maxThreadCacheEntries")));

			if (request.getParameter("captchaEnabled") != null) {
				config.setCaptchaEnabled(true);
			} else {
				config.setCaptchaEnabled(false);
			}

			if (request.getParameter("testServer") != null) {
				config.setTestServer(true);
			} else {
				config.setTestServer(false);
			}

			config.setMaxImagesPerPost(Integer.parseInt(request.getParameter("maxImagesPerPost")));
			config.setBanThreshold(Integer.parseInt(request.getParameter("banThreshold")));
			config.setMaxPollItems(Integer.parseInt(request.getParameter("maxPollItems")));

			config.setThreadIndexPath(request.getParameter("threadIndexPath"));
			config.setMessageIndexPath(request.getParameter("messageIndexPath"));
			config.setGeoDatabasePath(request.getParameter("geoDatabasePath"));
			config.setFileUploadRepository(request.getParameter("fileUploadRepository"));
			config.setFileUploadRepositoryUrl(request.getParameter("fileUploadRepositoryUrl"));

			if (request.getParameter("showLocationDataOnMessagesForSiteAdmins") != null) {
				config.setShowLocationDataOnMessagesForSiteAdmins(true);
			} else {
				config.setShowLocationDataOnMessagesForSiteAdmins(false);
			}

			if (request.getParameter("storeDatabaseConnectionInfo") != null) {
				config.setStoreDatabaseConnectionInfo(true);
			} else {
				config.setStoreDatabaseConnectionInfo(false);
			}

			if (request.getParameter("ssl") != null) {
				config.setEmailSsl(true);
			} else {
				config.setEmailSsl(false);
			}

			config.setSmtpServer(request.getParameter("smtpServer"));
			config.setSmtpPort(Integer.parseInt(request.getParameter("port")));
			config.setSmtpServerLoginId(request.getParameter("loginId"));
			config.setSmtpServerPassword(request.getParameter("password"));
			config.setDefaultStyleSheet(request.getParameter("defaultStyleSheet"));

			if (request.getParameter("supportSuggestBan") != null) {
				config.setSupportSuggestBan(true);
			} else {
				config.setSupportSuggestBan(false);
			}

			if (request.getParameter("suggestSimilarThreads") != null) {
				config.setSuggestSimilarThreads(true);
			} else {
				config.setSuggestSimilarThreads(false);
			}

			if (request.getParameter("displayAdminLogToUsers") != null) {
				config.setDisplayAdminLogToUsers(true);
			} else {
				config.setDisplayAdminLogToUsers(false);
			}

			if (request.getParameter("displayAdminLogToSiteAdmins") != null) {
				config.setDisplayAdminLogToSiteAdmins(true);
			} else {
				config.setDisplayAdminLogToSiteAdmins(false);
			}

			if (request.getParameter("logSiteWideAdminActions") != null) {
				config.setLogSiteWideAdminActions(true);
			} else {
				config.setLogSiteWideAdminActions(false);
			}

			if (request.getParameter("allowChangeOfUserName") != null) {
				config.setAllowChangeOfUserName(true);
			} else {
				config.setAllowChangeOfUserName(false);
			}

			if (request.getParameter("adminsCanSeePictures") != null) {
				config.setAdminsCanSeePictures(true);
			} else {
				config.setAdminsCanSeePictures(false);
			}

			if (request.getParameter("enableBlogView") != null) {
				config.setEnableBlogView(true);
			} else {
				config.setEnableBlogView(false);
			}

			if (request.getParameter("deleteOldUsers") != null) {
				config.setDeleteOldUsers(true);
			} else {
				config.setDeleteOldUsers(false);
			}

			if (request.getParameter("showPasswordImmediately") != null) {
				config.setShowPasswordImmediately(true);
			} else {
				config.setShowPasswordImmediately(false);
			}

			if (request.getParameter("supportFileUploads") != null) {
				config.setSupportFileUploads(true);
			} else {
				config.setSupportFileUploads(false);
			}

			if (request.getParameter("onlySupportImageUploads") != null) {
				config.setOnlySupportImageUploads(true);
			} else {
				config.setOnlySupportImageUploads(false);
			}

			if (request.getParameter("usersCanSeeTheirRecentPosts") != null) {
				config.setUsersCanSeeTheirRecentPosts(true);
			} else {
				config.setUsersCanSeeTheirRecentPosts(false);
			}

			if (request.getParameter("showNotWorksafeLinkForAdmins") != null) {
				config.setShowNotWorksafeLinkForAdmins(true);
			} else {
				config.setShowNotWorksafeLinkForAdmins(false);
			}

			if (request.getParameter("threadsPosts") != null) {
				config.setThreadsPosts(true);
				Site.setThread("Thread");
				Site.setPost("Post");
			} else {
				config.setThreadsPosts(false);
				Site.setThread("Question");
				Site.setPost("Answer");
			}

			if (request.getParameter("reportOnSockpuppets") != null) {
				config.setReportOnSockpuppets(true);
			} else {
				config.setReportOnSockpuppets(false);
			}

			if (request.getParameter("siteOpenOnStartup") != null) {
				config.setSiteOpenOnStartup(true);
			} else {
				config.setSiteOpenOnStartup(false);
			}

			if (request.getParameter("validateBBCode") != null) {
				config.setValidateBBCode(true);
			} else {
				config.setValidateBBCode(false);
			}

			/* Set the site domain name */

			String domainName = request.getServerName();

			if (request.getServerPort() != 80) {
				domainName += ":" + request.getServerPort();
			}

			Logger.log(new Date(), "<b><span class='red'>Setting domain name to:</span></b> " + domainName, null, LogMessageType.SYSTEM);

			Configuration.getInstance().setDomainName(domainName);

			InputChecker.refresh();
			Validator.refresh();

			config.store();

			RequestDispatcher dispatcher = request.getRequestDispatcher("/Admin/AdminEditSiteConfigurationServlet");
			dispatcher.forward(request, response);

		} catch (SQLException e) {
			throw new ServletException(e);
		}

	}

}
